package com.my.study.utils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

public class Base64Util {

    public static String fileToBase64(File file) {
        if (file == null) {
            return null;
        }
        try {
            //获取文件名
            String fileName = file.getName();
            StringBuffer result = new StringBuffer(fileName);
            byte[] bytes = Files.readAllBytes(Paths.get(String.valueOf(file)));
            String baseResult = Base64.getEncoder().encodeToString(bytes);
            return result.append(",").append(baseResult).toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String base64StrListToString(List<String> base64StrList){
        if(Objects.isNull(base64StrList)){
            return null;
        }
        String result = "";
        for(String string:base64StrList){
            if(!"".equals(result)){
                result = result + ";" + string;
            }else{
                result = string;
            }
        }
        return result;
    }

    public static void base64ToFile(String filePath,String base64){
        FileOutputStream outputStream = null;
        try {
            if(Objects.nonNull(filePath) && Objects.nonNull(base64)){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String fileName = sdf.format(new Date())+".xls";
                File file = new File(filePath,fileName);
                byte[] bytes = Base64.getDecoder().decode(base64);
                ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
                byte[] buff = new byte[1024];
                outputStream = new FileOutputStream(file);
                int buffRead = 0;
                while((buffRead = inputStream.read(buff)) != -1){
                    outputStream.write(buff,0,buffRead);
                };
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
